<template>
  <div class="container">
    <Breadcrumb :items="['站点管理', '充电桩管理']" />
    <a-card
      class="general-card"
      :title="stationName ? `${stationName} - 充电桩管理` : '充电桩管理'"
    >
      <template #extra>
        <a-button type="primary" @click="goBack">
          <template #icon>
            <icon-arrow-left />
          </template>
          返回站点列表
        </a-button>
      </template>
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="searchForm"
            label-align="left"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-layout="inline"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="name" :label="$t('充电桩名称')">
                  <a-input
                    v-model="searchForm.name"
                    :placeholder="$t('请输入充电桩名称')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="status" :label="$t('状态')">
                  <a-select
                    v-model="searchForm.status"
                    :placeholder="$t('请选择状态')"
                    allow-clear
                  >
                    <a-option :value="1">{{ $t('在线') }}</a-option>
                    <a-option :value="0">{{ $t('离线') }}</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="16">
                <a-space>
                  <a-button type="primary" @click="search">
                    <template #icon>
                      <icon-search />
                    </template>
                    {{ $t('搜索') }}
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    {{ $t('重置') }}
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 32px" direction="vertical" />
        <a-col :flex="'200px'" style="text-align: right">
          <a-space>
            <a-button type="primary" @click="goToSingleAdd">
              <template #icon>
                <icon-plus />
              </template>
              {{ $t('新增充电桩') }}
            </a-button>
            <a-button type="outline" @click="openImportDialog">
              <template #icon>
                <icon-upload />
              </template>
              {{ $t('批量导入') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />

      <!-- 设备卡片列表 -->
      <div class="device-list">
        <a-row :gutter="[24, 24]">
          <a-col :span="8" v-for="device in deviceList" :key="device.id">
            <div
              class="device-card-wrapper"
              :class="{ 'device-offline': device.status === 0 }"
            >
              <!-- 充电桩标题和状态 -->
              <div class="device-card-header">
                <div class="device-info">
                  <div class="device-icon">
                    <icon-thunderbolt />
                  </div>
                  <div class="device-title">
                    <h3 class="device-name">{{ device.name }}</h3>
                    <div class="device-meta">
                      <span class="device-code">编号：{{ device.code }}</span>
                    </div>
                    <div class="device-meta">
                      <span class="create-date"
                        >创建：{{ formatTime(device.createDate) }}</span
                      >
                    </div>
                  </div>
                </div>
                <div class="device-status">
                  <a-tag
                    :color="device.status === 1 ? 'green' : 'red'"
                    size="medium"
                  >
                    {{ device.status === 1 ? '在线' : '离线' }}
                  </a-tag>
                </div>
              </div>

              <!-- 充电枪列表 -->
              <div class="device-card-content">
                <div class="gun-section-header">
                  <span class="gun-section-title">充电枪</span>
                  <span class="gun-count"
                    >{{ device.socketCount || 0 }} 个</span
                  >
                </div>

                <a-spin :loading="loadingGuns" tip="加载中...">
                  <template v-if="device.guns && device.guns.length > 0">
                    <div class="gun-list">
                      <div
                        v-for="gun in device.guns"
                        :key="gun.id"
                        class="gun-item"
                        :class="{
                          'gun-idle': gun.status === 0,
                          'gun-plugged': gun.status === 1,
                          'gun-charging': gun.status === 2,
                          'gun-unplugged': gun.status === 3,
                          'gun-reserved': gun.status === 4,
                          'gun-fault': gun.status === 5,
                        }"
                      >
                        <div class="gun-status-indicator"></div>
                        <div class="gun-body">
                          <div class="gun-header">
                            <span class="gun-name">{{ gun.socketName }}</span>
                            <a-tag
                              size="small"
                              :color="getStatusColor(gun.status)"
                            >
                              {{ getStatusText(gun.status) }}
                            </a-tag>
                          </div>
                          <div class="gun-details">
                            <div class="gun-params-grid">
                              <div class="gun-param-item">
                                <div class="param-label">枪编号</div>
                                <div class="param-value"
                                  >{{ Number(gun.code) + 1 }}号枪</div
                                >
                              </div>
                              <div class="gun-param-item" v-if="gun.powerTotal">
                                <div class="param-label">剩余电量</div>
                                <div class="param-value"
                                  >{{ gun.powerTotal }}
                                  <span class="param-unit">kWh</span></div
                                >
                              </div>
                              <div class="gun-param-item" v-if="gun.timeTotal">
                                <div class="param-label">剩余时间</div>
                                <div class="param-value"
                                  >{{ gun.timeTotal }}
                                  <span class="param-unit">分钟</span></div
                                >
                              </div>
                            </div>
                            <template v-if="gun.status === 1">
                              <div class="charging-progress-section">
                                <div class="charging-title">充电进行中</div>
                                <div class="gun-params-grid">
                                  <div
                                    class="gun-param-item"
                                    v-if="gun.orderNumber"
                                  >
                                    <div class="param-label">订单号</div>
                                    <div class="param-value order-number">{{
                                      gun.orderNumber
                                    }}</div>
                                  </div>
                                  <div
                                    class="gun-param-item"
                                    v-if="gun.orderCreateDate"
                                  >
                                    <div class="param-label">开始时间</div>
                                    <div class="param-value">{{
                                      formatTime(gun.orderCreateDate)
                                    }}</div>
                                  </div>
                                  <div
                                    class="gun-param-item"
                                    v-if="gun.lastUseTime"
                                  >
                                    <div class="param-label">最后使用</div>
                                    <div class="param-value">{{
                                      formatTime(gun.lastUseTime)
                                    }}</div>
                                  </div>
                                </div>
                              </div>
                            </template>
                            <template v-if="gun.status === 2">
                              <div class="charging-progress-section">
                                <div class="charging-title">充电进行中</div>
                                <div class="gun-params-grid">
                                  <div
                                    class="gun-param-item"
                                    v-if="gun.orderNumber"
                                  >
                                    <div class="param-label">订单号</div>
                                    <div class="param-value order-number">{{
                                      gun.orderNumber
                                    }}</div>
                                  </div>
                                  <div
                                    class="gun-param-item"
                                    v-if="gun.orderCreateDate"
                                  >
                                    <div class="param-label">开始时间</div>
                                    <div class="param-value">{{
                                      formatTime(gun.orderCreateDate)
                                    }}</div>
                                  </div>
                                  <div
                                    class="gun-param-item"
                                    v-if="gun.lastUseTime"
                                  >
                                    <div class="param-label">最后使用</div>
                                    <div class="param-value">{{
                                      formatTime(gun.lastUseTime)
                                    }}</div>
                                  </div>
                                </div>
                              </div>
                            </template>
                          </div>
                        </div>
                      </div>
                    </div>
                  </template>
                  <div v-else class="empty-guns">
                    <a-empty :image-size="64" description="暂无充电枪" />
                  </div>
                </a-spin>
              </div>

              <!-- 操作按钮 -->
              <div class="device-card-footer">
                <div class="device-action-buttons">
                  <div class="action-group">
                    <a-tooltip content="查看详情">
                      <a-button
                        type="primary"
                        size="small"
                        shape="round"
                        @click="viewDeviceDetail(device)"
                      >
                        <template #icon><icon-eye /></template>
                        详情
                      </a-button>
                    </a-tooltip>
                    <a-tooltip content="管理充电枪">
                      <a-button
                        type="primary"
                        status="success"
                        size="small"
                        shape="round"
                        @click="viewGuns(device)"
                      >
                        <template #icon><icon-edit /></template>
                        充电枪
                      </a-button>
                    </a-tooltip>
                    <a-tooltip content="查看订单">
                      <a-button
                        type="primary"
                        status="warning"
                        size="small"
                        shape="round"
                        @click="viewDeviceOrders(device)"
                      >
                        <template #icon><icon-file /></template>
                        订单
                      </a-button>
                    </a-tooltip>
                  </div>
                  <div class="action-group">
                    <!-- <a-tooltip content="编辑设备">
                      <a-button type="primary" status="normal" size="small" shape="round" @click="openEditDialog(device)">
                        <template #icon><icon-settings /></template>
                        编辑
                      </a-button>
                    </a-tooltip> -->
                    <a-tooltip content="转发日志">
                      <a-button
                        type="outline"
                        size="small"
                        shape="round"
                        @click="viewForwardLog(device)"
                      >
                        <template #icon><icon-history /></template>
                        日志
                      </a-button>
                    </a-tooltip>
                  </div>
                </div>
              </div>
            </div>
          </a-col>

          <!-- 空状态 -->
          <a-col :span="24" v-if="deviceList.length === 0">
            <div class="empty-state">
              <a-empty description="暂无设备数据" />
            </div>
          </a-col>
        </a-row>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <a-pagination
          v-model:current="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          show-page-size
          :page-size-options="pagination.pageSizeOptions"
          @change="onPageChange"
          @page-size-change="onPageSizeChange"
        />
      </div>
    </a-card>

    <!-- 新增/编辑设备对话框 -->
    <a-modal
      v-model:visible="visible"
      :title="isEdit ? '编辑充电桩' : '新增充电桩'"
      :mask-closable="false"
      :unmount-on-close="false"
      width="600px"
      class="device-modal"
    >
      <charging-form
        ref="chargingFormRef"
        v-if="visible"
        :charging-group-id="stationId"
        :group-name="stationName"
        :is-edit="isEdit"
        :edit-data="{
          id: currentDevice?.id,
          code: currentDevice?.code || '',
          name: currentDevice?.name || '',
          socketCount: currentDevice?.socketCount || 1,
          chargingGroupId: stationId || 0,
        }"
      />
      <template #footer>
        <div class="modal-footer">
          <a-space>
            <a-button @click="handleCancel">取消</a-button>
            <a-button type="primary" :loading="loading" @click="handleSubmit">
              {{ isEdit ? '保存' : '提交' }}
            </a-button>
          </a-space>
        </div>
      </template>
    </a-modal>

    <!-- 设备详情对话框 -->
    <a-modal
      v-model:visible="detailVisible"
      title="充电桩详情"
      @cancel="detailVisible = false"
      :footer="false"
      width="700px"
    >
      <div v-if="currentDevice" class="device-detail">
        <a-descriptions :column="2" bordered size="large">
          <a-descriptions-item label="充电桩名称">{{
            currentDevice.name
          }}</a-descriptions-item>
          <a-descriptions-item label="充电桩编号">{{
            currentDevice.code
          }}</a-descriptions-item>
          <a-descriptions-item label="设备状态">
            <a-tag :color="currentDevice.status === 1 ? 'green' : 'red'">
              {{ currentDevice.status === 1 ? '在线' : '离线' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="插座数量">{{
            currentDevice.socketCount
          }}</a-descriptions-item>
          <a-descriptions-item label="总功率">{{
            currentDevice.totalPower
              ? currentDevice.totalPower / 1000 + ' kW'
              : '未知'
          }}</a-descriptions-item>
          <a-descriptions-item label="启用状态">{{
            currentDevice.enableFlag === 1 ? '启用' : '禁用'
          }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">{{
            formatTime(currentDevice.createDate)
          }}</a-descriptions-item>
          <a-descriptions-item label="更新时间">{{
            formatTime(currentDevice.updateDate)
          }}</a-descriptions-item>
          <a-descriptions-item label="启动语音">{{
            currentDevice.startupVoice || '未设置'
          }}</a-descriptions-item>
        </a-descriptions>

        <div class="detail-footer">
          <a-button type="primary" @click="detailVisible = false"
            >关闭</a-button
          >
        </div>
      </div>
    </a-modal>

    <!-- 导入对话框 -->
    <import-dialog
      v-model:visible="importVisible"
      :charging-group-id="stationId"
      :group-name="stationName"
      @success="handleImportSuccess"
    />
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted, nextTick } from 'vue';
  import { Message, Modal } from '@arco-design/web-vue';
  import { useRoute, useRouter } from 'vue-router';
  import useLoading from '@/hooks/loading';
  import type { FormInstance } from '@arco-design/web-vue';
  import {
    IconThunderbolt,
    IconBulb,
    IconEye,
    IconEdit,
    IconSettings,
    IconDelete,
    IconSync,
    IconLink,
    IconFile,
    IconClockCircle,
    IconHistory,
    IconDashboard,
    IconPlus,
    IconUpload,
  } from '@arco-design/web-vue/es/icon';
  import {
    getChargingPileList,
    getGunList,
    getGunRealtimeData,
    type ChargingPileItem,
    type GunItem,
    type PageParams,
  } from '@/api/station/device';
  import {
    getChargingList,
    addCharging,
    updateCharging,
    deleteCharging,
    type ChargingData,
    type ChargingListParams,
  } from '@/api/charging';
  import ImportDialog from '@/views/charging/list/components/import-dialog.vue';
  import ChargingForm from '@/views/charging/list/components/charging-form.vue';

  // 获取路由参数
  const route = useRoute();
  const router = useRouter();
  const stationId = ref<number | null>(null);
  const stationName = ref<string>('');

  // 加载状态
  const { loading, setLoading } = useLoading();

  // 对话框状态
  const visible = ref(false);
  const detailVisible = ref(false);
  const isEdit = ref(false);
  const formRef = ref<FormInstance | null>(null);
  const currentDevice = ref<ChargingData | null>(null);
  const loadingGuns = ref(false);

  // 设备列表
  const deviceList = ref<ChargingData[]>([]);

  // 搜索表单
  const searchForm = reactive({
    name: '',
    status: undefined as number | undefined,
  });

  // 分页
  const pagination = reactive({
    total: 0,
    current: 1,
    size: 12,
    defaultPageSize: 12,
    showTotal: true,
    pageSizeOptions: [12, 24, 36, 48],
  });

  // 表单数据
  interface FormState {
    id?: number;
    name: string;
    code: string;
    pileType: number;
    locationDesc: string;
    ipAddress: string;
    manufacturer: string;
    model: string;
    status: number;
    remark: string;
    stationId: number;
    power: number;
    voltage: number;
    current: number;
    protocolType: string;
    port: number;
    longitude: number;
    latitude: number;
    gunCount: number;
  }

  const formInitialState: FormState = {
    name: '',
    code: '',
    pileType: 1,
    locationDesc: '',
    ipAddress: '',
    manufacturer: '',
    model: '',
    status: 0,
    remark: '',
    stationId: 0,
    power: 0,
    voltage: 0,
    current: 0,
    protocolType: '',
    port: 0,
    longitude: 0,
    latitude: 0,
    gunCount: 1,
  };

  // 添加上一次的表单数据
  const lastFormData = ref<Partial<FormState>>({});

  const form = reactive<FormState>({ ...formInitialState });

  // 表单验证规则
  const rules = {
    name: [{ required: true, message: '请输入充电桩名称' }],
    code: [{ required: true, message: '请输入充电桩编号' }],
    pileType: [{ required: true, message: '请选择充电类型' }],
    gunCount: [{ required: true, message: '请输入枪口数量' }],
  };

  // 获取充电枪类型文本
  function getChargeTypeText(type: number) {
    switch (type) {
      case 1:
        return '国标';
      case 2:
        return '欧标';
      case 3:
        return '美标';
      case 4:
        return '特斯拉';
      default:
        return '未知类型';
    }
  }

  // 获取充电桩类型文本
  function getDeviceTypeText(type: number) {
    switch (type) {
      case 1:
        return '直流快充';
      case 2:
        return '交流慢充';
      case 3:
        return '超级快充';
      default:
        return '未知类型';
    }
  }

  // 获取状态文本
  function getStatusText(status: number) {
    switch (status) {
      case 0:
        return '空闲';
      case 1:
        return '已插枪';
      case 2:
        return '充电中';
      case 3:
        return '未拔枪';
      case 4:
        return '预约中';
      case 5:
        return '故障';
      default:
        return '未知状态';
    }
  }

  // 获取状态颜色
  function getStatusColor(status: number) {
    switch (status) {
      case 0:
        return 'green'; // 空闲 - 绿色
      case 1:
        return 'blue'; // 已插枪 - 蓝色
      case 2:
        return 'cyan'; // 充电中 - 青色
      case 3:
        return 'orange'; // 未拔枪 - 橙色
      case 4:
        return 'purple'; // 预约中 - 紫色
      case 5:
        return 'red'; // 故障 - 红色
      default:
        return 'gray';
    }
  }

  // 格式化时间
  function formatTime(timestamp?: number) {
    if (!timestamp) return '未知';
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }

  // 获取充电桩列表数据
  async function fetchData() {
    setLoading(true);
    try {
      const params = {
        pageNum: pagination.current,
        pageSize: pagination.size,
        chargingGroupId: stationId.value,
        name: searchForm.name || undefined,
        status: searchForm.status,
      };

      console.log('请求充电桩列表参数:', params);
      const response = await getChargingPileList(params);
      console.log('获取充电桩列表响应:', response);

      if (response.data && response.data.records) {
        deviceList.value = response.data.records;
        pagination.total = response.data.total;
        console.log('更新后的分页数据:', pagination);

        // 获取每个充电桩的充电枪
        await fetchGunsForDevices();
      } else {
        console.error('API返回数据格式异常:', response);
        Message.error('获取数据失败，返回格式异常');
      }
    } catch (error) {
      console.error('获取充电桩列表失败:', error);
      Message.error('获取充电桩列表失败');
    } finally {
      setLoading(false);
    }
  }

  // 获取所有充电桩的充电枪数据
  async function fetchGunsForDevices() {
    loadingGuns.value = true;
    try {
      const promises = deviceList.value.map(async (device) => {
        try {
          // 获取充电枪基本数据
          const response = await getGunList(device.id);
          const guns = response.data || [];

          // 获取充电枪实时数据
          const gunsWithRealtime = await Promise.all(
            guns.map(async (gun: GunItem) => {
              try {
                const realTimeResponse = await getGunRealtimeData(gun.id);
                const realTimeData = realTimeResponse.data || {};
                return {
                  ...gun,
                  ...realTimeData,
                };
              } catch (error) {
                console.error(`获取充电枪 ${gun.id} 实时数据失败:`, error);
                return gun;
              }
            })
          );

          return { ...device, guns: gunsWithRealtime };
        } catch (error) {
          console.error(`获取充电桩 ${device.id} 的充电枪数据失败:`, error);
          return { ...device, guns: [] };
        }
      });

      deviceList.value = await Promise.all(promises);
    } catch (error) {
      console.error('批量获取充电枪数据失败:', error);
    } finally {
      loadingGuns.value = false;
    }
  }

  // 搜索
  function search() {
    pagination.current = 1;
    fetchData();
  }

  // 重置搜索条件
  function reset() {
    searchForm.name = '';
    searchForm.status = undefined;
    pagination.current = 1;
    fetchData();
  }

  // 分页变化
  function onPageChange(current: number) {
    pagination.current = current;
    console.log('页码变化，当前页:', current);
    fetchData();
  }

  // 每页条数变化
  function onPageSizeChange(size: number) {
    pagination.size = size;
    pagination.current = 1;
    console.log('每页条数变化，新的每页条数:', size);
    fetchData();
  }

  // 新增充电桩
  function goToSingleAdd() {
    isEdit.value = false;
    currentDevice.value = null;
    visible.value = true;
  }

  // 打开编辑对话框
  async function openEditDialog(device: ChargingData) {
    isEdit.value = true;
    currentDevice.value = device;
    visible.value = true;
    // 等待DOM更新后设置表单值
    nextTick(() => {
      if (chargingFormRef.value) {
        chargingFormRef.value.setFormData({
          code: device.code,
          name: device.name,
          socketCount: device.socketCount,
          chargingGroupId: device.chargingGroupId,
        });
      }
    });
  }

  // 查看设备详情
  function viewDeviceDetail(device: ChargingData) {
    currentDevice.value = device;
    detailVisible.value = true;
  }

  // 查看充电枪
  function viewGuns(device: ChargingData) {
    router.push({
      path: '/station/device/gun',
      query: {
        deviceId: device.id,
        deviceName: device.name,
        stationId: stationId.value,
        stationName: stationName.value,
      },
    });
  }

  // 查看设备订单
  function viewDeviceOrders(device: ChargingData) {
    router.push({
      path: '/charging/order',
      query: {
        stationId: stationId.value,
        stationName: stationName.value,
        pileId: device.id,
        pileName: device.name,
      },
    });
  }

  // 查看转发日志
  function viewForwardLog(device: ChargingData) {
    router.push({
      path: '/station/device/forward-log',
      query: {
        deviceId: device.id,
        deviceName: device.name,
        code: device.code,
        stationId: stationId.value,
        stationName: stationName.value,
        pileName: searchForm.name,
        pileType: searchForm.pileType,
        status: searchForm.status,
        current: pagination.current,
        size: pagination.size,
      },
    });
  }

  // 表单引用
  const chargingFormRef = ref();

  // 处理表单提交
  async function handleSubmit() {
    if (!chargingFormRef.value) return;

    try {
      // 表单验证
      await chargingFormRef.value.validate();

      // 获取表单数据
      const formData = chargingFormRef.value.getFormData();

      setLoading(true);

      // 调用API保存数据
      const response = await (isEdit.value
        ? updateCharging(formData)
        : addCharging(formData));

      if (response.code === 200) {
        Message.success(isEdit.value ? '编辑充电桩成功' : '新增充电桩成功');
        visible.value = false;
        fetchData(); // 刷新列表
      } else {
        Message.error(
          response.message ||
            (isEdit.value ? '编辑充电桩失败' : '新增充电桩失败')
        );
      }
    } catch (error) {
      console.error(
        isEdit.value ? '编辑充电桩失败:' : '新增充电桩失败:',
        error
      );
      Message.error(isEdit.value ? '编辑充电桩失败' : '新增充电桩失败');
    } finally {
      setLoading(false);
    }
  }

  // 处理取消
  function handleCancel() {
    visible.value = false;
    if (chargingFormRef.value) {
      chargingFormRef.value.resetForm();
    }
  }

  // 返回站点列表
  function goBack() {
    if (stationId.value) {
      // 如果有站点ID，返回到站点详情页
      router.push({
        path: '/car/charging/group',
        query: {
          stationId: stationId.value,
          stationName: stationName.value,
        },
      });
    } else {
      // 如果没有站点ID，直接返回站点列表
      router.push('/car/charging/group');
    }
  }

  // 格式化充电时长(分钟转为小时分钟)
  function formatDuration(minutes: number): string {
    if (!minutes && minutes !== 0) return '- -';

    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;

    if (hours > 0) {
      return `${hours}小时${mins}分钟`;
    } else {
      return `${mins}分钟`;
    }
  }

  // 获取SOC颜色类名
  function getSocColorClass(soc: number): string {
    if (soc >= 70) {
      return 'soc-high';
    } else if (soc >= 30) {
      return 'soc-medium';
    } else {
      return 'soc-low';
    }
  }

  // 导入对话框
  const importVisible = ref(false);

  // 打开导入对话框
  function openImportDialog() {
    if (!stationId.value) {
      Message.warning('请先选择站点');
      return;
    }
    importVisible.value = true;
  }

  // 导入成功处理
  function handleImportSuccess() {
    Message.success('批量导入成功');
    fetchData(); // 刷新列表
    importVisible.value = false; // 关闭对话框
  }

  onMounted(() => {
    console.log('组件挂载，初始化分页配置');
    // 获取路由参数
    if (route.query.chargingGroupId) {
      stationId.value = Number(route.query.chargingGroupId);
    } else if (route.query.groupId) {
      stationId.value = Number(route.query.groupId);
    } else if (route.query.stationId) {
      stationId.value = Number(route.query.stationId);
    }

    if (route.query.stationName) {
      stationName.value = route.query.stationName as string;
    } else if (route.query.groupName) {
      stationName.value = route.query.groupName as string;
    }

    // 恢复查询条件
    if (route.query.name) {
      searchForm.name = route.query.name as string;
    }
    if (route.query.pileType) {
      searchForm.pileType = Number(route.query.pileType);
    }
    if (route.query.status) {
      searchForm.status = Number(route.query.status);
    }
    if (route.query.current) {
      pagination.current = Number(route.query.current);
    }
    if (route.query.size) {
      pagination.size = Number(route.query.size);
    }

    console.log('初始化后的分页配置:', pagination);
    console.log('初始化后的stationId:', stationId.value);

    // 获取设备列表
    fetchData();
  });
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }

  .device-list {
    margin-top: 16px;
    margin-bottom: 24px;

    // 响应式布局优化
    @media (max-width: 1200px) {
      .arco-col {
        flex: 0 0 50%;
        max-width: 50%;
      }
    }

    @media (max-width: 768px) {
      .arco-col {
        flex: 0 0 100%;
        max-width: 100%;
      }
    }
  }

  .device-card-wrapper {
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
    background-color: #fff;
    overflow: hidden;
    transition: all 0.3s;
    height: 100%;
    display: flex;
    flex-direction: column;

    &:hover {
      transform: translateY(-6px);
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);

      .device-card-footer {
        background-color: rgba(0, 96, 255, 0.04);
      }
    }

    &.device-offline {
      opacity: 0.9;
      background-color: #fafafa;

      .device-card-header {
        background-color: #f5f5f5;
      }

      .device-card-footer {
        background-color: #f0f0f0;
      }
    }

    .device-card-header {
      padding: 20px;
      background: linear-gradient(
        to right,
        rgba(0, 96, 255, 0.03),
        rgba(0, 96, 255, 0.08)
      );
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid rgba(0, 0, 0, 0.05);

      .device-info {
        display: flex;
        align-items: center;

        .device-icon {
          width: 48px;
          height: 48px;
          display: flex;
          justify-content: center;
          align-items: center;
          background: linear-gradient(135deg, #1890ff, #096dd9);
          border-radius: 12px;
          margin-right: 16px;

          :deep(svg) {
            font-size: 24px;
            color: #fff;
          }
        }

        .device-title {
          .device-name {
            font-size: 18px;
            font-weight: 600;
            margin: 0 0 6px 0;
            color: var(--color-text-1);
          }

          .device-meta {
            font-size: 13px;
            color: var(--color-text-3);
            line-height: 1.5;
            margin-top: 4px;

            .device-code {
              color: var(--color-text-2);
              font-weight: 500;
            }

            .create-date {
              color: var(--color-text-3);
            }
          }
        }
      }

      .device-status {
        .arco-tag {
          padding: 0 12px;
          height: 28px;
          line-height: 28px;
          font-weight: 500;
        }
      }
    }

    .device-card-content {
      flex: 1;
      padding: 20px;
      background-color: #fff;

      .gun-section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        .gun-section-title {
          font-size: 16px;
          font-weight: 600;
          color: var(--color-text-1);
        }

        .gun-count {
          font-size: 13px;
          color: var(--color-text-3);
          background-color: var(--color-fill-2);
          padding: 2px 8px;
          border-radius: 10px;
        }
      }

      .gun-list {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
        gap: 12px;

        .gun-item {
          display: flex;
          background-color: #f9f9f9;
          border-radius: 8px;
          overflow: hidden;
          border-left: 4px solid transparent;
          transition: all 0.2s;

          &:hover {
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
            transform: translateY(-2px);
          }

          &.gun-idle {
            border-left-color: #52c41a; // 绿色
          }

          &.gun-plugged {
            border-left-color: #13c2c2; // 青色
          }

          &.gun-charging {
            border-left-color: #13c2c2; // 青色
          }

          &.gun-unplugged {
            border-left-color: #faad14; // 橙色
          }

          &.gun-reserved {
            border-left-color: #9254de; // 紫色
          }

          &.gun-fault {
            border-left-color: #f5222d; // 红色
          }

          .gun-body {
            flex: 1;
            padding: 12px;

            .gun-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 10px;

              .gun-name {
                font-size: 15px;
                font-weight: 500;
                color: var(--color-text-1);
              }
            }

            .gun-details {
              display: flex;
              flex-direction: column;
              gap: 12px;

              .gun-params-grid {
                display: grid;
                grid-template-columns: repeat(2, 1fr);
                gap: 8px 12px;
              }

              .gun-param-item {
                display: flex;
                flex-direction: column;
                gap: 2px;
              }

              .param-label {
                font-size: 11px;
                color: var(--color-text-3);
              }

              .param-value {
                font-size: 14px;
                font-weight: 500;
                color: var(--color-text-2);
              }

              .param-unit {
                font-size: 12px;
                font-weight: normal;
                color: var(--color-text-3);
                margin-left: 1px;
              }

              .param-value.highlight {
                color: var(--color-primary);
              }

              .param-value.order-number {
                font-family: monospace;
                font-size: 12px;
                background-color: var(--color-fill-2);
                padding: 1px 4px;
                border-radius: 3px;
                max-width: 100%;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }

              .charging-progress-section {
                margin-top: 4px;
                background-color: rgba(19, 194, 194, 0.08);
                border-radius: 6px;
                padding: 8px 10px;
              }

              .charging-title {
                font-size: 12px;
                font-weight: 500;
                color: var(--color-primary);
                margin-bottom: 6px;
                display: flex;
                align-items: center;

                &::before {
                  content: '';
                  display: inline-block;
                  width: 6px;
                  height: 6px;
                  border-radius: 50%;
                  background-color: var(--color-primary);
                  margin-right: 5px;
                  animation: pulse 1.5s infinite;
                }
              }

              .soc-progress-bar {
                width: 100%;
                height: 4px;
                background-color: var(--color-fill-2);
                border-radius: 2px;
                margin-top: 2px;
                overflow: hidden;
              }

              .soc-progress-inner {
                height: 100%;
                transition: width 0.3s ease;

                &.soc-high {
                  background: linear-gradient(90deg, #52c41a, #1fab47);
                }

                &.soc-medium {
                  background: linear-gradient(90deg, #faad14, #d48806);
                }

                &.soc-low {
                  background: linear-gradient(90deg, #ff4d4f, #cf1322);
                }
              }
            }
          }
        }
      }

      .empty-guns {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 120px;
        background-color: #fafafa;
        border-radius: 8px;
      }
    }

    .device-card-footer {
      padding: 12px 20px;
      border-top: 1px solid rgba(0, 0, 0, 0.05);
      display: flex;
      justify-content: flex-end;
      background-color: #fafafa;
      transition: background-color 0.3s ease;

      .device-action-buttons {
        display: flex;
        flex-direction: row;
        gap: 8px;
        width: 100%;
        flex-wrap: wrap;
        justify-content: center;

        .action-group {
          display: flex;
          gap: 8px;
          justify-content: center;
          flex-wrap: wrap;

          .arco-btn {
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.08);
            transition: all 0.2s;
            min-width: 80px;
            font-weight: 400;

            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
            }

            &[status] {
              &:hover {
                opacity: 0.85;
              }
            }
          }
        }
      }
    }
  }

  .empty-state {
    padding: 40px 0;
    text-align: center;
  }

  .pagination-container {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }

  .device-modal {
    :deep(.arco-modal-header) {
      border-bottom: 1px solid var(--color-border-2);
      padding: 16px 20px;

      .arco-modal-title {
        font-size: 18px;
        font-weight: 500;
      }
    }

    :deep(.arco-modal-body) {
      padding: 20px;
    }
  }

  .device-form {
    .form-footer {
      display: flex;
      justify-content: center;
      margin-top: 24px;

      .arco-space {
        .arco-btn {
          min-width: 80px;
        }
      }
    }
  }

  .device-detail {
    .detail-footer {
      margin-top: 24px;
      text-align: center;
    }
  }

  .card-header-extra {
    display: flex;
    align-items: center;
    gap: 8px;

    .delete-btn {
      margin-left: 4px;
      padding: 0;
      color: var(--color-text-3);

      &:hover {
        color: rgb(var(--danger-6));
      }
    }
  }

  @keyframes pulse {
    0% {
      transform: scale(0.8);
      opacity: 0.8;
    }
    50% {
      transform: scale(1.2);
      opacity: 1;
    }
    100% {
      transform: scale(0.8);
      opacity: 0.8;
    }
  }

  // 全局按钮样式优化
  :deep(.arco-btn) {
    border-radius: 5px;

    &.arco-btn-shape-round {
      border-radius: 20px;
    }
  }
</style>
